# coding: utf-8

from flask import request, jsonify

from .. import db
from ..forms import NotChoices

from . import op_bp
from .models import Area, Audio, User
from .constant import AreaType, UserType, SEMGroup
from app.axb.models import VirtualNumber, QueryCallNumberRecord
from app.axb.constant import VirtualNumberValid


@op_bp.route('/ajax/get_cities')
def ajax_get_cities():
    """
    add by zhouhl 2017-07-24
    AJAX接口，根据省份取城市列表
    """
    prov_name = request.args.get("prov_name", None)
    if prov_name is None:
        return jsonify(choices=[])
    prov_area = Area.query.filter_by(name=prov_name).first()
    if prov_area is None:
        return jsonify(choices=[])

    cities = Area.query.filter(
        Area.id.like('{}%'.format(str(prov_area.id)[:2])),
        Area.type == AreaType.CITY.value,
    ).all()

    choices = [{'id': -1, 'name': ''}] + \
        [{'id': i.name, 'name': i.name} for i in cities]
    return jsonify(choices=choices)


@op_bp.route('/ajax/get_user_nickname')
def ajax_get_user_nickname():
    """
    add by zhouhl 2017-07-24
    AJAX接口，根据电话查询用户是否存在
    存在则返回用户昵称，否则返回空字符串
    """
    mobile = request.args.get("user_mobile", None)
    if mobile:
        user = User.query.filter_by(mobile=mobile, deleted_at=0).first()
        return jsonify(nickname=user.nickname if user else '')
    else:
        return jsonify(nickname='')


@op_bp.route('/ajax/get_user_id')
def ajax_get_user_id():
    """
    add by zhouhl 2018-08-03
    AJAX接口，根据电话查询用户ID
    """
    mobile = request.args.get("user_mobile", None)

    # add by zhouhl 2017-10-11 查询虚拟关系
    # TODO by zhouhl 类似的功能需要重构！！！
    # NOTE by zhouhl 2017-12-04 使用虚拟号外呼时，查询客户信息
    tmp_val_num = VirtualNumber.get_by_args(
        tel_x=mobile,
        valid=VirtualNumberValid.VALID.value,
    )
    # NOTE by zhouhl 2017-12-04 tel_a 需要排除七陌的固话号码
    if (
        tmp_val_num
        and tmp_val_num.tel_a not in SEMGroup.values()
        and tmp_val_num.tel_b == ''
    ):
        mobile = tmp_val_num.tel_a
    else:
        # add by zhouhl 2017-12-04 新版首页设置了多个axn虚拟号引导至400客服电话
        # 需要查询 query_call_number_records 来获取客户真实号码
        tmp_query_call_number_record = QueryCallNumberRecord.query.filter_by(
            called=mobile
        ).order_by(
            QueryCallNumberRecord.id.desc()
        ).first()
        if tmp_query_call_number_record:
            mobile = tmp_query_call_number_record.caller

    if mobile:
        user = User.query.filter_by(mobile=mobile, deleted_at=0).first()
        # 如果用户不存在，直接新建用户
        if not user:
            new_user = User(
                area_id=0,
                type=UserType.CLIENT.value,
                mobile=mobile,
                nickname='新客户(请填写)',
            )
            db.session.add(new_user)
            db.session.flush()
            user = new_user
        return jsonify(id=user.id)
    else:
        return jsonify(id='')


@op_bp.route('/ajax/get_user_audios')
def ajax_get_user_audios():
    """
    add by zhouhl 2017-07-25
    AJAX接口，根据电话查询用户录音
    存在则返回录音id、录音地址和录音日期，否则返回空字符串
    """
    mobile = request.args.get("user_mobile", None)
    user = User.query.filter_by(mobile=mobile, deleted_at=0).first()
    if user:
        audios = user.audios.order_by(Audio.id.desc())
    else:
        # 如果是新用户，则直接查Audio表
        audios = Audio.query.filter_by(
            mobile=mobile, deleted_at=0).order_by(Audio.id.desc()).all()

    result = [
        {
            'id': NotChoices[0][0],
            'src': NotChoices[0][1],
            'record_date': '',
        },
    ]
    for i in audios:
        tmp_i = {
            'id': i.id,
            'src': 'http://audio.wanpinghui.com/' + i.audio,
            'record_date': str(i.record_date),
        }
        result.append(tmp_i)
    return jsonify(result)


